﻿using DataModels.Dto;
using DataModels.Dto.ParkingLot;
using DataModels.Entities.Base;
using DataModels.Entities.House;
using DataModels.Entities.ParkingLot;
using DataModels.Enums.Bill;
using DataModels.Enums.ParkingLot;
using Dm.util;
using Services.Payment;
using SqlSugar;
using System.Text.Json;
using Utils;

namespace Services.ParkingLot
{
    public class ParkingSpaceService(SqlSugarClient db, PaymentCenterService paymentCenterService) : BaseService(db)
    {
        protected readonly PaymentCenterService _paymentCenterService = paymentCenterService;
        // 获取车位信息
        public ResponseModel GetParkingSpaceInfo(Guid ProjectUUID)
        {
            var organId = GetOrganIdBySIGE(ProjectUUID);
            var custId = GetCustIdBySIGE();

            var res = db.Queryable<CustomerHouseRelation, ParkingSpace, Customer, Projects>(
                    (chr, ps, c, p) => new JoinQueryInfos(
                        JoinType.Left, chr.ObjId == ps.ParkingId,
                        JoinType.Left, chr.CustId == c.CustId,
                        JoinType.Left, chr.OrganId == p.CommunityId
                    ))
                .Where((chr, ps, c, p) => chr.OrganId == organId)
                .Where((chr, ps, c, p) => chr.RelType == "3" && chr.CustId == custId)
                .Select((chr, ps, c, p) => new GetParkingSpaceInfoResponse
                {
                    ParkingSpaceId = ps.UUID,
                    ParkingId = ps.ParkingId,
                    ProjectName = p.ProjectName,
                    SpaceNumber = ps.SpaceNumber,
                    AreaType = ps.ParkingType.ToString(), // 注意大小写
                    EndDate = ps.ExpDate,
                })
                .ToList();
            return Success(res);
        }


        public ResponseModel GetParkingSpaceList(ParkingRequestDto requestDto)
        {
            int total = 0;
            int organId = int.Parse(GetOrganIdBySIGE(requestDto.ProjectUUID));
            var list = db.Queryable<ParkingSpace>().Where(x => x.CommunityId == organId)
                .OrderByDescending(x=>x.ObjType)
                .OrderBy(x=>x.ObjStatus)
                .ToPageList(requestDto.PageNumber, requestDto.PageSize, ref total);
            return Success(new
            {
                Total = total,
                Comments = list
            });
        }


        // 修改车位信息
        public ResponseModel EditParkingSpaceInfo(EditParkingSpaceInfo info)
        {
            ParkingSpaceUserRelation model = db.Queryable<Projects, ParkingLotTable, ParkingSpace, ParkingSpaceUserRelation>((p, pkl, ps, psur) => new object[]
            {
                JoinType.Left,p.UUID == pkl.ProjectUUID,
                JoinType.Left,pkl.UUID == ps.ParkingLotUUID,
                JoinType.Left,ps.UUID == psur.ParkingSpaceUUID

            })
                .Where((p, pkl, ps, psur) => psur.UserUUID == UserUUID)
                .Where((p, pkl, ps, psur) => ps.UUID == info.ParkingSpaceId)
                // 关系持续
                .Where((p, pkl, ps, psur) => psur.Status == ParkingSpaceUserRelationStatus.Active)
                .Select((p, pkl, ps, psur) => psur)
                .First()
                ;
            if (model == null)
            {
                return Error("没有找到有效的车位信息");
            }
            model.Remark = info.Remark;
            model.UpdateTime = DateTime.Now;
            db.Updateable(model).ExecuteCommand();
            return Success("修改车位信息成功");
        }

        // 获取缴费信息
        public ResponseModel GetParkingSpacePaymentInfo(Guid ProjectId, Guid ParkingSpaceId)
        {
            var res = db.Queryable<Projects, ParkingLotTable, ParkingSpace, ParkingSpaceUserRelation>((p, pkl, ps, psur) => new object[]
           {
                JoinType.Left,p.UUID == pkl.ProjectUUID,
                JoinType.Left,pkl.UUID == ps.ParkingLotUUID,
                JoinType.Left,ps.UUID == psur.ParkingSpaceUUID

           })
               .Where((p, pkl, ps, psur) => p.UUID == ProjectId)
               .Where((p, pkl, ps, psur) => psur.UserUUID == UserUUID)
               .Where((p, pkl, ps, psur) => ps.UUID == ParkingSpaceId)
               // 关系持续
               .Where((p, pkl, ps, psur) => psur.Status == ParkingSpaceUserRelationStatus.Active)
               .Select((p, pkl, ps, psur) => new { p, pkl, ps, psur })
               .First()
               ;

            //调用四格api获取实际优惠
            List<ParkingSpacePaymentCoupon> Coupons =
            [
                new ParkingSpacePaymentCoupon
                {
                    CouponId = Guid.NewGuid().ToString(),
                    Money = 0
                },
            ];
            GetParkingSpacePaymentInfoResponse response = new()
            {
                ParkingSpaceId = ParkingSpaceId,
                EndDate = res.psur.EndDate,
                MonthlyFee = res.pkl.MonthlyFee,
                ParkingSpaceFullAddress = res.p.ProjectName + res.ps.ParkingSpaceFullAddress,
                Coupons = Coupons

            };

            return Success(response);
        }

        // 车位缴费
        public ResponseModel ParkingSpacePayment(ParkingSpacePayment info)
        {
            try
            {
                var res = db.Queryable<Projects, ParkingLotTable, ParkingSpace, ParkingSpaceUserRelation>((p, pkl, ps, psur) => new object[]
                {
                    JoinType.Left,p.UUID == pkl.ProjectUUID,
                    JoinType.Left,pkl.UUID == ps.ParkingLotUUID,
                    JoinType.Left,ps.UUID == psur.ParkingSpaceUUID
                })
                   .Where((p, pkl, ps, psur) => p.UUID == info.ProjectId)
                   .Where((p, pkl, ps, psur) => psur.UserUUID == UserUUID)
                   .Where((p, pkl, ps, psur) => ps.UUID == info.ParkingSpaceId)
                   // 关系持续
                   .Where((p, pkl, ps, psur) => psur.Status == ParkingSpaceUserRelationStatus.Active)
                   // 有结束日期
                   .Where((p, pkl, ps, psur) => psur.EndDate != null)
                   .Select((p, pkl, ps, psur) => new { p, pkl, ps, psur })
                   .First()
                   ;
                if (res == null)
                {
                    return Error("未找到需要缴费的车位");
                }

                // 需要根据使用的优惠规则计算优惠
                //
                //
                //

                // 月费
                decimal MonthlyFee = res.pkl.MonthlyFee;
                // 月份
                int month = info.Month;
                // 应付
                decimal PayableAmount = MonthlyFee * month;
                // 这里减去优惠

                string remark = $"车位缴费：{month}个月";
                db.BeginTran();


                Guid billuuid = _paymentCenterService.CreateBill(UserUUID, BusinessType.ParkingSpacePay, info.PayWay, info.PaySerialId, PaymentType.Payment, 600.01m, info.PayDesc, remark, JsonSerializer.Serialize(info));
                // 调用四格支付确认接口
                //

                // 需要获取到实际付款金额 , 这里是测试
                decimal PayAmount = PayableAmount;
                // 计算应付实付是否相等
                if (PayableAmount == PayAmount)
                {
                    _paymentCenterService.BillSuccess(billuuid);

                }
                else
                {
                    //这里退款
                    return Error("应付实付有差额，已退款");
                }

                //支付成功业务操作

                ParkingSpaceUserRelation model = res.psur;


                // 已过期
                if (model.EndDate < DateTime.Now)
                {
                    // 过期很久是否要单独处理
                    //
                    //
                    //

                    model.StartDate = DateTime.Now;
                    model.EndDate = DateTime.Now.AddMonths(info.Month);
                }
                else
                {
                    model.EndDate = model.EndDate.Value.AddMonths(info.Month);
                }
                db.Updateable(model).ExecuteCommand();
                db.CommitTran();

                return Success();

            }
            catch (Exception ex)
            {
                db.RollbackTran();
                return Error("缴费失败：" + ex.Message);
            }
        }

        /// <summary>
        /// 车位认证提交
        /// </summary>
        /// <returns></returns>
        public ResponseModel ParkingSpaceSubmitCertification()
        {
            return Success();
        }
    }
}
